<template>

    <el-button type="danger" @click="handleBatchWrong">
        批量纠错
    </el-button>
    &nbsp;

    <el-button @click="importExcelQuestion" type="primary">
        导入题目
    </el-button>
    &nbsp;


    <el-dropdown>
        <el-button type="success">
            导出至excel<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <template #dropdown>
            <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click="handleExport(false)">导出全部</el-dropdown-item>
                <el-dropdown-item @click="handleExport(true)">导出所选项</el-dropdown-item>
            </el-dropdown-menu>
        </template>
    </el-dropdown>

    &nbsp;


    <el-table style="width:1100px" :data="tableData" stripe @selection-change="handleSelectionChange"
        @sort-change="sort" @filter-change="filterChange">
        <el-table-column fixed="left" label="编号" width="100">
            <!-- prop="code" -->
            <template #default="scope">
                <el-link @click="handleClick(scope.row)" type="primary">{{ scope.row.code }}</el-link>
            </template>
        </el-table-column>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="typeName" :filters="Type" column-key="type" width="100" label="题目类型">
            <template #default="scope">
                <el-tag>{{ scope.row.typeName }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="question" label="题目" width="500">
            <template #header>
                <el-input v-model="queryParam.question" size="small" placeholder="题目搜索" :prefix-icon="Search"
                    @change="filterQuestion" />
            </template>
        </el-table-column>
        <el-table-column prop="optionA" label="A" />
        <el-table-column prop="optionB" label="B" />
        <el-table-column prop="optionC" label="C" />
        <el-table-column prop="optionD" label="D" />
        <el-table-column prop="answerOption" label="答案" />
        <el-table-column prop="creationDate" label="创建时间" sortable="custom" width="200" />
        <el-table-column fixed="right" label="操作" width="180">
            <template #header>
                <el-switch v-model="queryParam.isMaster" active-color="#13ce66" inactive-color="#ff4949"
                    inactive-value="0" active-text="过滤已掌握" active-value="1" @change="switchChange()">
                </el-switch>
            </template>
            <template #default="scope">
                <el-button size="small" type="danger" @click="handleWrong(scope.row)">
                    纠错
                </el-button>
                <el-button v-if="!scope.row.master" size="small" type="success" @click="handleMaster(scope.row.id)">
                    已掌握
                </el-button>
                <el-button v-else size="small" type="warning" @click="handleNoMaster(scope.row.masterId)">
                    待增强
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="pageSizes"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />

    <!-- 问题纠错 -->
    <el-dialog v-model="wrongDialogVisible" title="纠错">
        <el-form ref="wrongFormRef" :model="wrongForm" :rules="rules" class="demo-ruleForm">
            <el-form-item label="错误信息" prop="remark">
                <el-input v-model="wrongForm.remark" placeholder="请输入错误信息" type="textarea" />
            </el-form-item>
        </el-form>
        <el-button type="success" @click="handleConfirm">确定</el-button>
        <el-button type="info" @click="handleCancel">取消</el-button>
    </el-dialog>

    <!-- 批量问题纠错 -->
    <el-dialog v-model="batchWrongDialogVisible" title="批量问题纠错">
        <el-form ref="batchWrongFormRef" :model="batchWrongForm" :rules="rules" class="demo-ruleForm">
            <el-form-item label="错误信息" prop="remark">
                <el-input v-model="batchWrongForm.remark" placeholder="请输入错误信息" type="textarea" />
            </el-form-item>
        </el-form>
        <el-button type="success" @click="handleBatchConfirm">确定</el-button>
        <el-button type="info" @click="handleBatchCancel">取消</el-button>
    </el-dialog>

    <!-- 详情页 -->
    <el-dialog v-model="detailDialogVisible" title="题目详情" fullscreen v-if="detailDialogVisible">
        <questionDetail :question="currentItem"></questionDetail>
    </el-dialog>

    <!-- 导入题目对话框 -->
    <el-dialog v-model="dialogUploadVisible" title="导入题目">
        <el-link href="template/questionTemplate.xlsx" type="info">请按模板导入数据，若没有模板，请点击此处下载</el-link>
        <el-upload :limit="1" :accept="'.xlsx,.xls'" class="upload-demo" drag action="/knowledge/importQuestion"
            :data="data" :on-success="handleImportExcel">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                将文件拖到此处或<em>点击上传</em>,仅支持xlsx或xls文件格式
            </div>
        </el-upload>
    </el-dialog>

</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage } from 'element-plus'
import axios from 'axios';
import questionDetail from './questionDetail.vue';
import { Type } from '../../util/type'
import {
    UploadFilled,
    Search

} from '@element-plus/icons-vue'

const pageSizes = ref([10, 25, 50, 100])
const pageSize = ref(pageSizes.value[0]);
const tableData = ref([])
const ids = ref([])
const total = ref(0)
const currentPage = ref(1)
const wrongDialogVisible = ref(false)

const batchWrongDialogVisible = ref(false)

const batchWrongFormRef = ref();

const detailDialogVisible = ref(false)
const dialogUploadVisible = ref(false)

const queryParam = ref({
    isMaster: 0,
    orderColumn: "",
    orderSort: "",
    typeList: [],
    ids: [],
    question: ""
})

const wrongFormRef = ref();
const wrongForm = reactive({
    remark: '',
    questionId: 0
})

const batchWrongForm = reactive({
    remark: '',

})

const rules = reactive({
    remark: [
        { required: true, message: '请输入错误信息', trigger: 'blur' }
    ]
})

const currentItem = ref({})

onMounted(() => {
    getList(currentPage.value, pageSize.value)
})
const getList = async (currentPage, pageSize) => {
    var res = await axios.post(`/knowledge/getQuestionInfoByPage?page=${currentPage}&size=${pageSize}`, queryParam.value)
    if (res.data.code === 200) {
        tableData.value = res.data.data.records
        total.value = res.data.data.total
    } else {
        ElMessage.error(res.data.msg)
    }
}

const handleSizeChange = () => {
    currentPage.value = 1;
    getList(currentPage.value, pageSize.value)
}

const handleCurrentChange = () => {
    getList(currentPage.value, pageSize.value)
}

const handleSelectionChange = (row) => {
    ids.value = row.map(r => r.id)

}

const data = {
    "token": localStorage.getItem("token")
}

// 单个纠错对话框
const handleWrong = async (row) => {
    wrongDialogVisible.value = true
    currentItem.value = row;
}

// 批量纠错对话框
const handleBatchWrong = () => {
    if (ids.value.length === 0) {
        ElMessage.warning("至少选择1条数据")
        return false;
    }

    batchWrongDialogVisible.value = true
}

// 问题纠错
const handleConfirm = async () => {
    wrongForm.questionId = currentItem.value.id;
    var res = await axios.post(`/knowledge/wrong/save`, wrongForm)
    if (res.data.code === 200) {
        ElMessage.success("操作成功")
        wrongDialogVisible.value = false;
        wrongForm.remark = ''
    } else {
        ElMessage.error(res.data.msg)
    }
}

const handleBatchConfirm = async () => {
    var res = await axios.post(`/knowledge/wrong/batchSave`, {
        remark: batchWrongForm.remark,
        questionIdList: ids.value
    })
    if (res.data.code === 200) {
        ElMessage.success("操作成功")
        wrongDialogVisible.value = false;
        batchWrongForm.remark = ''
    } else {
        ElMessage.error(res.data.msg)
    }
}


// 标记为我已掌握
const handleMaster = async (id) => {
    var res = await axios.put(`/knowledge/master/save/${id}`)
    if (res.data.code === 200) {
        ElMessage.success("操作成功")
        getList(currentPage.value, pageSize.value)
    } else {
        ElMessage.error(res.data.msg)
    }
}

// masterId
const handleNoMaster = async (id) => {
    var res = await axios.delete(`/knowledge/master/del/${id}`)
    if (res.data.code === 200) {
        ElMessage.success("操作成功")
        getList(currentPage.value, pageSize.value)
    } else {
        ElMessage.error(res.data.msg)
    }
}

// 纠错对话框取消
const handleBatchCancel = () => {
    batchWrongDialogVisible.value = false;
}

const handleCancel = () => {
    wrongDialogVisible.value = false;
}

const handleClick = (item) => {
    detailDialogVisible.value = true
    currentItem.value = item;
}

// 笔记记录
const takeNote = () => {
    console.log("takeNote")
}


// 是否掌握的回调函数
const switchChange = () => {
    currentPage.value = 1;
    getList(currentPage.value, pageSize.value)
}

const sort = (column) => {
    currentPage.value = 1;
    queryParam.value.orderColumn = column.prop;
    queryParam.value.orderSort = column.order
    getList(currentPage.value, pageSize.value)
}

const importExcelQuestion = () => {
    dialogUploadVisible.value = true;
}

const handleImportExcel = (resp) => {
    if (resp.code === 200) {
        ElMessage.success("导入成功")
        dialogUploadVisible.value = false;
        currentPage.value = 1;
        getList(currentPage.value, pageSize.value)
    } else {
        ElMessage.error(resp.msg)
    }

}

const typeChange = () => {
    currentPage.value = 1;
    getList(currentPage.value, pageSize.value)
}

const handleExport = async (flag) => {
    if (flag) {
        queryParam.value.ids = ids;
    }
    var response = await axios.post(`knowledge/exportExcel`, queryParam.value, {
        responseType: 'blob'
    })
    queryParam.value.ids = [];
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '题库.xlsx');
    document.body.appendChild(link);
    link.click();


}

const filterChange = (filter) => {
    queryParam.value.typeList = filter["type"];

    currentPage.value = 1;
    getList(currentPage.value, pageSize.value)
}

const filterQuestion = (filter) => {
    queryParam.value.question = filter;

    currentPage.value = 1;
    getList(currentPage.value, pageSize.value)
}

</script>
<style></style>